package com.buobao.spring.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;

import java.text.SimpleDateFormat;
import java.util.Date;

//切面类
public class MethodAspect {
    //切面方法
    //joinpoint连接点
    public void printExecutionTime(JoinPoint joinPoint) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
        String now = simpleDateFormat.format(new Date());
        String className = joinPoint.getTarget().getClass().getName();//获取目标类名
        String methodName = joinPoint.getSignature().getName();//获取目标方法名
        System.out.println("------>"+now+" "+className+"."+methodName+"()");
    }

    //after-returning有两个参数，后面一个是方法执行的返回值
    public void afterReturning(JoinPoint joinPoint,Object s) {
        System.out.println("afterReturning:"+s);
    }

    public void afterThrowing(JoinPoint joinPoint,Exception e) {
        System.out.println("afterThrowing:"+e);
    }

    public Object check(ProceedingJoinPoint joinPoint) {
        try {
            long startTime = new Date().getTime();
            Object obj = joinPoint.proceed();//控制目标方法执行
            long endTime = new Date().getTime();
            long duratime = endTime - startTime;
            if (duratime>5) {
                System.out.println("执行时间过长:"+duratime);
            }
            return obj; //将原方法返回
        } catch (Throwable e) {
            throw new RuntimeException(e); //这个异常应该要抛出去，方便后续处理
        }
    }
}
